package com.banzhi.shop.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.AddbankCard.Bank_Data;
import com.banzhi.shop.entity.PersonDetail.Person_Data;
import com.banzhi.shop.model.CallBack.AddBankCardCallBack;
import com.banzhi.shop.model.CallBack.SendCodeCallBack;
import com.banzhi.shop.model.IAddbankCardModel;
import com.banzhi.shop.model.ISendCodeModel;
import com.banzhi.shop.model.Impl.AddbankCardImpl;
import com.banzhi.shop.model.Impl.SendCodeImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.lljjcoder.citypickerview.widget.CityPicker;

import org.json.JSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.carbswang.android.numberpickerview.library.NumberPickerView;

/**
 * 添加银行卡
 */
public class AddBankCardActivity extends BaseActivity implements View.OnClickListener, AddBankCardCallBack, SendCodeCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 开户地区布局
     */
    private LinearLayout lldiqu;
    /**
     * 开户地区
     */
    private TextView tvdiqu;
    /**
     * 选择银行的布局
     */
    private LinearLayout llbank;
    /**
     * 银行
     */
    private TextView tvbank;
    /**
     * 发送验证码
     */
    private TextView tvsendcode;
    /**
     * 支行名输入框
     */
    private EditText etbankname;
    /**
     * 持卡人姓名输入框
     */
    private EditText etpersonname;
    /**
     * 银行卡输入框
     */
    private EditText etbankcardnumber;
    /**
     * 手机号
     */
    private TextView tvphone;
    /**
     * 验证码输入框
     */
    private EditText etcode;
    /**
     * 提交
     */
    private Button btn_save;

    private String province;
    private String city;
    private String district;
    private String tvaddress;
    private String bank;

    private Handler handler = new MyHandler();
    private Timer timer;

    private IAddbankCardModel model;
    private ISendCodeModel sendcodemodel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bank_card);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new AddbankCardImpl();
        model.getData(this);
        sendcodemodel = new SendCodeImpl();
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        lldiqu = (LinearLayout) findViewById(R.id.ll_diqu);
        tvdiqu = (TextView) findViewById(R.id.tv_diqu);
        llbank = (LinearLayout) findViewById(R.id.ll_bank);
        tvbank = (TextView) findViewById(R.id.tv_bank);
        etbankname = (EditText) findViewById(R.id.et_bankname);
        etpersonname = (EditText) findViewById(R.id.et_name);
        etbankcardnumber = (EditText) findViewById(R.id.et_bankcardnumber);
        etcode = (EditText) findViewById(R.id.et_code);
        tvphone = (TextView) findViewById(R.id.tv_phone);
        tvsendcode = (TextView) findViewById(R.id.tv_send_code);
        btn_save = (Button) findViewById(R.id.btn_save);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        lldiqu.setOnClickListener(this);
        llbank.setOnClickListener(this);
        tvsendcode.setOnClickListener(this);
        btn_save.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_diqu:
                choiceCity();
                break;
            case R.id.ll_bank:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                model.getBank(this);
                break;
            case R.id.tv_send_code:
                if (!"".equals(tvphone.getText().toString().trim())) {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    sendcodemodel.getData(tvphone.getText().toString().trim(), this);
                } else {
                    model.getData(this);
                }
                break;
            case R.id.btn_save:
                if(!ASUtils.isCanUse(bank)){
                    ToastUtils.makeToastShort("请选择开户银行");
                }else if(!ASUtils.isCanUse(province)){
                    ToastUtils.makeToastShort("请选择开户地区");
                }else if(!ASUtils.isCanUse(etbankname.getText().toString().trim())){
                    ToastUtils.makeToastShort("请输入支行名称");
                }else if(!ASUtils.isCanUse(etpersonname.getText().toString().trim())){
                    ToastUtils.makeToastShort("请输入持卡人姓名");
                }else if(!ASUtils.isCanUse(etbankcardnumber.getText().toString().trim())){
                    ToastUtils.makeToastShort("请输入银行卡号");
                }else if(!ASUtils.isCanUse(etcode.getText().toString().trim())){
                    ToastUtils.makeToastShort("请先输入验证码");
                }else{
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    model.onsave(bank,province,city,district,etbankname.getText().toString().trim(),
                            etpersonname.getText().toString().trim(),etbankcardnumber.getText().toString().trim(),
                            tvphone.getText().toString().trim(),etcode.getText().toString().trim(),this);
                }
                break;

        }

    }

    private int number = 60;

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            number--;
            tvsendcode.setText(number + "");
            if (number < 0) {
                tvsendcode.setClickable(true);
                tvsendcode.setText("发送验证码");
                number = 60;
                timer.cancel();
            }
        }
    }

    /**
     * 选择银行
     */
    private void choiceBankpopupwindow(final String[] str) {
        View contentView = LayoutInflater.from(AddBankCardActivity.this).inflate(R.layout.popupwindow_bank, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);

        NumberPickerView npv_education = (NumberPickerView) contentView.findViewById(R.id.picker_education);
        //将数据显示在显示器上
        npv_education.refreshByNewDisplayedValues(str);

        final Button btntrue = (Button) contentView.findViewById(R.id.btn_true);
        final Button btncancel = (Button) contentView.findViewById(R.id.btn_cancel);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        bank = str[0];
        NumberPickerView.OnValueChangeListener nplistener = new NumberPickerView.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
                bank = str[newVal];

            }
        };
        npv_education.setOnValueChangedListener(nplistener);
        btntrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvbank.setText(bank);
                popWindow.dismiss();
            }
        });
        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 选择省市区
     */
    private void choiceCity() {
        CityPicker cityPicker = new CityPicker.Builder(this)
                .textSize(20)
                .title("地址选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#1FAFB4")
                .titleTextColor("#000000")
                .backgroundPop(0xa0000000)
                .confirTextColor("#000000")
                .cancelTextColor("#000000")
                .province("安徽省")
                .city("合肥市")
                .district("蜀山区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();

        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                province = citySelected[0];
                //城市
                city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                district = citySelected[2];
                //邮编
                String code = citySelected[3];

                tvdiqu.setText(province + city + district);
            }

            @Override
            public void onCancel() {
                ToastUtils.makeToastShort("已取消");
            }
        });
    }

    /**
     * @param object 获取银行卡界面
     */
    @Override
    public void ongetBankSuccess(Object object) {
        List<Bank_Data> bankdata = (List<Bank_Data>) object;
        String[] str = new String[bankdata.size()];
        for (int i = 0; i < bankdata.size(); i++) {
            str[i] = bankdata.get(i).getBankname();
        }
        //选择银行的popupwindow
        choiceBankpopupwindow(str);
    }

    @Override
    public void ongetBankError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void ongetDataSuccess(Object object) {
        Person_Data data = (Person_Data) object;
        if (ASUtils.isCanUse(data.getMobile())) {
            tvphone.setText(data.getMobile());
        }
    }

    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object
     * 保存数据成功
     */
    @Override
    public void onsaveSuccess(Object object) {
        JSONObject json = (JSONObject) object;
        ToastUtils.makeToastShort(json.optString("msg"));
    }

    /**
     * @param object
     * 保存数据失败
     */
    @Override
    public void onsaveError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void sendCodeSuccess(Object object) {
        tvsendcode.setClickable(false);
        if (timer == null) {
            timer = new Timer();
        } else {
            timer.cancel();
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                handler.sendMessage(msg);
            }
        }, 0, 998);
    }

    @Override
    public void sendCodeError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
